package com.yan.project.controller;

import com.yan.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangYan
 * @description:
 * @date 2021/3/15 16:11
 */
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     *
     * @Author WangYan
     * @Date 2021/3/15 16:15
     */
    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    /**
     * 注册接⼝，true成功，false失败
     *
     * @Author WangYan
     * @Date 2021/3/15 16:15
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        Boolean register = userService.register(email, password, code);
        if (register) {
            String token = userService.getToken(email);
            Cookie cookie = new Cookie("token", token);
            response.addCookie(cookie);
        }
        return register;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     * 返回 ：邮箱地址
     *
     * @Author WangYan
     * @Date 2021/3/15 16:15
     */
    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password) {
        if (userService.login(email, password)) {
            String token = userService.getToken(email);
            Cookie cookie = new Cookie("token", token);
            response.addCookie(cookie);
            return email;
        }
        return null;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     * 返回 ：邮箱地址
     *
     * @Author WangYan
     * @Date 2021/3/15 16:15
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        return userService.info(token);
    }

    @Value(value = "${testMessage}")
    private String defaultZone;

    @GetMapping("/defaultZone")
    public String defaultZone() {
        System.out.println("请求到了后台 defaultZone");
        return defaultZone;
    }

}
